package ace.module.upms.core.impl.dao.aggregate.impl;

import ace.cmp.core.constants.CoreConstant;
import ace.module.upms.core.impl.dao.aggregate.UpmsRoleAggregate;
import ace.module.upms.core.impl.dao.entity.QUpmsRole;
import ace.module.upms.core.impl.dao.entity.QUpmsRoleAccount;
import ace.module.upms.core.impl.dao.entity.UpmsRole;
import ace.module.upms.core.impl.dao.repository.UpmsRoleRepository;
import com.querydsl.core.types.ExpressionUtils;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 角色对象 aggregate implement.
 *
 * @author Caspar
 */
@Slf4j
@AllArgsConstructor
@Component
public class UpmsRoleAggregateImpl implements UpmsRoleAggregate {

  private final UpmsRoleRepository upmsRoleRepository;

  @Override
  public List<UpmsRole> getByUpmsApIdAndIamAccountId(Long upmsAppId, Long iamAccountId) {
    return this.upmsRoleRepository.queryMany(sqlQuery -> {
      QUpmsRole qUpmsRole = new QUpmsRole("role");
      QUpmsRoleAccount qUpmsRoleAccount = new QUpmsRoleAccount("role_account");
      return sqlQuery
          .distinct()
          .select(qUpmsRole)
          .from(qUpmsRole)
          .innerJoin(qUpmsRoleAccount)
          .on(qUpmsRole.id.eq(qUpmsRoleAccount.roleId))
          .where(ExpressionUtils.allOf(
              qUpmsRole.upmsAppId.eq(upmsAppId),
              qUpmsRole.deleteFlag.eq(CoreConstant.DELETE_FLAG_NOT),
              qUpmsRoleAccount.upmsAppId.eq(upmsAppId),
              qUpmsRoleAccount.iamAccountId.eq(iamAccountId),
              qUpmsRoleAccount.deleteFlag.eq(CoreConstant.DELETE_FLAG_NOT)
          ));
    });
  }
}